%This is a function that runs the standard mixed logit
function y=clogit_star(beta, Data, n)


%Define some parameters to be used 
N=max(Data(:,1));
task=max(Data(:,2));
option=max(Data(:,3));
L=size(beta,2);
x=zeros(L,1);                         %FOCs to be summed up in the loop
z=zeros(L,1);
y=zeros(L,1);
omega=.1;
b=1/N;

id=n;
for taskid=1:task                       %for each task
    if sum(Data((id-1)*task*option+(taskid-1)*option+1:(id-1)*task*option+taskid*option,4))~=12
        %extract the relevant data from Data and idcharac
        rank=Data((id-1)*task*option+(taskid-1)*option+1:(id-1)*task*option+taskid*option,4);
        w=Data((id-1)*task*option+(taskid-1)*option+1:(id-1)*task*option+taskid*option-1,5:5+L-option);
        w=[eye(option-1) w];

        %define the numerators of the likelihood
        numer(1:option-1,1)=exp(w*beta');

        %define the denominator 
        denom=sum(numer)+1;

        %set up the likelihood vector
        probi=numer/denom;

        %this is a matrix of weighted average values of w, to be used in
        %calculating FOCs
        wbar=probi'*w;

        %choice=options(rank==1);
        choice=zeros(option,1);
        choice(rank==1)=1;
        choice=choice(1:option-1);

        %Set up FOCs 
        x=x+w'*choice-wbar';
    end
end
x=(1-omega)*x;


for id=1:N                             %for each agent
    %s=idcharac(id,:);
            for taskid=1:task                       %for each task
                if sum(Data((id-1)*task*option+(taskid-1)*option+1:(id-1)*task*option+taskid*option,4))~=12
                    %extract the relevant data from Data and idcharac
                    rank=Data((id-1)*task*option+(taskid-1)*option+1:(id-1)*task*option+taskid*option,4);
                    w=Data((id-1)*task*option+(taskid-1)*option+1:(id-1)*task*option+taskid*option-1,5:5+L-option);
                    w=[eye(option-1) w];

                    %define the numerators of the likelihood
                    numer(1:option-1,1)=exp(w*beta');

                    %define the denominator 
                    denom=sum(numer)+1;

                    %set up the likelihood vector
                    probi=numer/denom;

                    %this is a matrix of weighted average values of w, to be used in
                    %calculating FOCs
                    wbar=probi'*w;

                    choice=zeros(option,1);
                    choice(rank==1)=1;
                    choice=choice(1:option-1);

                    
                    %Set up FOCs 
                    z=z+w'*choice-wbar';
                end
            end
end

z=omega*b*z;

y=x+z;
    
